﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows;
using Caliburn.Micro;
using GTServices.Entities;
using GTServices.Model;
using GTServices.WPF.Client.Controls;
using GTServices.Model.Extensions;
using GTServices.WPF.Client.ViewModels.Entities;
using GTServices.WPF.Client.Interfaces;

namespace GTServices.WPF.Client.ViewModels
{
    public class SelectItemsViewModel : Screen
    {

        public String FilterString { get; set; }

        public List<ISelectable> Selectables { get; set; } 


        public ListCollectionView CategoryCollectionView { get; set; }
        public ListCollectionView PatternCollectionView { get; set; }
        public ListCollectionView LanguageCollectionView { get; set; }

        Dictionary<String, ListCollectionView> _collectionsDictoinary; 


        public SelectItemsViewModel()
        {
            _collectionsDictoinary = new Dictionary<string, ListCollectionView>(); 

            CategoryCollectionView = new ListCollectionView(ModelViewModels.Instance.CategoryViewModels);
            CategoryCollectionView.SortDescriptions.Add(new System.ComponentModel.SortDescription("Category.Name", System.ComponentModel.ListSortDirection.Ascending));
            
            _collectionsDictoinary.Add("issue", CategoryCollectionView); 

           

            PatternCollectionView = new ListCollectionView(ModelViewModels.Instance.PatternViewModels);
            _collectionsDictoinary.Add("pattern", PatternCollectionView); 

            LanguageCollectionView = new ListCollectionView(ModelViewModels.Instance.LanguageViewModels);
            LanguageCollectionView.SortDescriptions.Add(new System.ComponentModel.SortDescription("Language.Name", System.ComponentModel.ListSortDirection.Ascending));
            LanguageCollectionView.Filter += new Predicate<object>(x =>
            {
                if (x is LanguageViewModel)
                {
                    LanguageViewModel lvm = x as LanguageViewModel;

                    return (lvm.Language.Name != "All");
                }
                return true;
            });

            _collectionsDictoinary.Add("language", LanguageCollectionView); 


            this.Selectables = new List<ISelectable>(); 
        }
        public void Select(String type)
        {
            ListCollectionView lcv = null;
            if (_collectionsDictoinary.TryGetValue(type.ToLower(), out lcv))
            {
                foreach (ISelectable selected in lcv)
                {
                    selected.IsSelected = true;
                }
                lcv.Refresh(); 
            }
        }
        //Lazyyyyy
        public void Deselect(String type)
        {
            ListCollectionView lcv = null;
            if (_collectionsDictoinary.TryGetValue(type.ToLower(), out lcv))
            {
                foreach (ISelectable selected in lcv)
                {
                    selected.IsSelected = false;
                }
                lcv.Refresh();
            }
        }
        public void FilterTextChanged(ActionExecutionContext context)
        {
            TextBox tb = context.Source as TextBox;
            if (tb != null)
            {
                this.FilterString = tb.Text;
            }
            if (!String.IsNullOrEmpty(this.FilterString))
            {
                CategoryCollectionView.Filter = new Predicate<Object>((x) =>
                {
                    CategoryViewModel c = x as CategoryViewModel;
                    
                    //Uncomment the language and sublanguage once the defaults are populated. 
                    if (c != null && c.Category.Name.ToLower().Contains(this.FilterString.ToLower()))
                        return true; 

                    return false;
                });

                PatternCollectionView.Filter = new Predicate<Object>((x) =>
                {
                    PatternViewModel p = x as PatternViewModel;

                    //Uncomment the language and sublanguage once the defaults are populated. 
                    if (p != null && 
                       (p.Pattern.PatternStr.ToLower().Contains(this.FilterString.ToLower())))
                        return true;

                    return false;
                });

                LanguageCollectionView.Filter = new Predicate<Object>((x) =>
                {

                    LanguageViewModel l = x as LanguageViewModel; 

                    if (l != null && 
                       (l.Language.Name.ToLower().Contains(this.FilterString.ToLower())))
                        return true;

                    return false;
                });

            }
            else
            {
                CategoryCollectionView.Filter = new Predicate<object>((x) => { return true; });
                PatternCollectionView.Filter = new Predicate<object>((x) => { return true; });
                LanguageCollectionView.Filter = new Predicate<object>((x) => { return true; });
            }
        }
        public void SortClick(ActionExecutionContext context)
        {
            Button b = context.Source as Button;
            if (b == null)
            {
                //TODO: Log + Error
                return;
            }
        }
        public void ClearSelectables(ActionExecutionContext aec)
        {
            if (aec.Source.GetType() == typeof(TabControl))
            {
                this.Selectables.Clear();
            }
        }
        public void SelectedSelectablesChanged(ActionExecutionContext context)
        {
            SelectionChangedEventArgs eventArgs = context.EventArgs as SelectionChangedEventArgs;
        
            if (eventArgs != null)
            {
                eventArgs.RemovedItems.Cast<ISelectable>().ForEach((x) =>
                {
                    Selectables.Remove(x);
                });

                eventArgs.AddedItems.Cast<ISelectable>().ForEach((x) =>
                {
                    Selectables.Add(x);
                });

                eventArgs.Handled = true;
            }
        }
        public void SelectSelectables(ActionExecutionContext context)
        {
            foreach (ISelectable pvm in this.Selectables)
            {
                pvm.IsSelected = !pvm.IsSelected;
            }
        }
        public void ExportSelectables(ActionExecutionContext context)
        {
            EntityCollection ec = new EntityCollection();
            this.Selectables.ForEach(x =>
            {
                if (x is IEntityViewModel)
                {
                    object o = (x as IEntityViewModel).Model;
                    if (o is BaseEntity)
                    {
                        ec.Entities.Add(o as BaseEntity);
                    }
                }
            });

            Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
            sfd.DefaultExt = "*.xml";
            sfd.Filter = "Xml documents (.xml)|*.xml"; // Filter files by extension 
            if (sfd.ShowDialog() == true)
            {
                try
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(System.IO.File.Open(sfd.FileName, System.IO.FileMode.Create)))
                    {
                        sw.Write(GTApplication.Instance.DataModel.GetEntityAsXml(ec));
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
       
        }
    }
}
